//
//  MobileTypeVC.m
//  EDF
//
//  Created by p on 2019/7/9.
//  Copyright © 2019年 p. All rights reserved.
//

#import "MobileTypeVC.h"
#import "PTCollectionViewCell.h"
#import "PTModel.h"
#import "LLWebViewController.h"
#import "EDPTGameDetailViewController.h"
@interface MobileTypeVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong)UICollectionView * collectionV;
@property(nonatomic,strong)NSMutableArray * dataSource;
@property (nonatomic,strong) NoNetworkView * workView;
@end
@implementation MobileTypeVC
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WHITECOLOR;
    [self.view addSubview:self.collectionV];
    // 上拉加载
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
         [self getPT_list];
    }];
    [header beginRefreshing];
    self.collectionV.mj_header = header;
   
 
}
- (void)viewWillAppear:(BOOL)animated
{
    [_collectionV reloadData];
}
- (void)getPT_list
{
    [self showLoadingAnimation];
    NSString * type;
    switch (_ptType) {
        case HOTType:
             type = @"HOT";
            break;
        case SAVEType:
            type = @"SAVE";
            break;
        case LATELYType:
            type = @"LATELY";
            break;
        case ALLType:
            type = @"ALL";
            break;
            
        default:
            break;
    }
    WeakSelf
    NSString  * game = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getGameAll"];
    [[SmileHttpTool sharedInstance] GET :game parameters:@{@"ptId":_modle.id,@"type":type} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        [self.collectionV.mj_header endRefreshing];
        [weakSelf stopLoadingAnimation];
        NSDictionary * dic = [self objectFromJSONString:responseObject];
        self.dataSource  = [PTModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        [self placeholderViewWithFrame:self.collectionV.frame NoNetwork:NO];
        [self.collectionV reloadData];
        
    } failure:^(id responseObject, NSError *error) {
        [weakSelf stopLoadingAnimation];
        [WJUnit showMessage:@"请求错误"];
        [self.collectionV.mj_header endRefreshing];
    }];

}
- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    if (self.dataSource.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:frame NoNetwork:NoNetwork];
        
        [_collectionV addSubview:_workView];
    }else
    {
        [_workView dissmiss];
    }
}
#pragma  mark -----懒加载
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (UICollectionView *)collectionV
{
    if (!_collectionV) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        _collectionV = [[UICollectionView alloc]initWithFrame:CGRectMake(0,
                                                                         0,
                                                                         UIScreenWidth,
                                                                         UIScreenHeight -kStatusBarAndNavigationBarHeight -RealValue_H(100) ) collectionViewLayout:layout];
        _collectionV.backgroundColor = RGBA(240, 240, 240, 1);
        _collectionV.delegate =self;
        _collectionV.dataSource= self;
        [_collectionV registerNib:[UINib nibWithNibName:@"PTCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PTCollectionViewCell"];
        _collectionV.showsVerticalScrollIndicator = NO;
        _collectionV.showsHorizontalScrollIndicator = NO;
    }
    return _collectionV;
    
}
#pragma mark---UICollectionViewDelgate
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PTCollectionViewCell *item = [self.collectionV dequeueReusableCellWithReuseIdentifier:@"PTCollectionViewCell" forIndexPath:indexPath];
    PTModel * model = _dataSource[indexPath.row];
    item.model = model;
    if ([model.istrial isEqualToString:@"是"]) {
        item.playBat.hidden = NO;

        item.top.constant =1;
    }else
    {
        item.playBat.hidden = YES;
        item.top.constant -=10;
    }
    WeakSelf
    [item.collBtn add_BtnClickHandler:^(NSInteger tag) {
        item.collBtn.userInteractionEnabled = NO;
        NSString  * game = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"addUserLikeGame"];
        [[SmileHttpTool sharedInstance] GET :game parameters:@{@"gameid":model.id} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject){
            
            NSDictionary * dic = [WJUnit dictionaryWithJsonString:responseObject];
            item.collBtn.userInteractionEnabled = YES;
             if ([[dic jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                 
                 if (model.isusergame) {
                     
            
                     ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"success" andTitleStr:@"取消收藏成功" andlightStr:@""];
                     [toast showLXAlertView];

                     model.isusergame = NO;
                     
                 }else
                 {
                     ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:2 andImageName:@"success" andTitleStr:@"收藏成功" andlightStr:@""];
                     [toast showLXAlertView];
                     model.isusergame = YES;
                 }
             }else
             {
                 [JMNotifyView showNotify:[dic jsonString:@"message"]  isSuccessful:NO];
             }
            
           [weakSelf.collectionV reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:indexPath.row inSection:0]]];
           
            
        } failure:^(id responseObject, NSError *error) {
            item.collBtn.userInteractionEnabled = YES;
            [WJUnit showMessage:@"请求错误"];
            
        }];
    }];
    [item.playBat add_BtnClickHandler:^(NSInteger tag) {
        
        [self getGameURLWithModel:model editInfo:@"offline"];
    }];
    item.getGameUrlBlock = ^(PTModel * _Nonnull modle) { //图片需要真实玩 需要登录的
        
        [self getGameURLWithModel:model editInfo:@"online"];
    };
    return item;
    
}
- (void)getGameURLWithModel:(PTModel *)model editInfo:(NSString *)editInfo
{
    if ([editInfo isEqualToString:@"online"]) {
         if (![DJLoginHelper sharedInstance].is_Login) {
             
             [[DJLoginHelper sharedInstance]dj_showLoginVC:self];
             return;
         }
    }
    [self showLoadingAnimation];
    NSString  * game = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getGameUrl"];
    NSDictionary * parame = @{@"mode":editInfo,@"gameid":model.gameid,@"plat_id":model.plat_id,@"gamecode":model.gamecode};
    [[SmileHttpTool sharedInstance] GET :game parameters:parame origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject){
        [self stopLoadingAnimation];
         NSDictionary * dic = [self objectFromJSONString:responseObject];
        if ([dic[@"statusCode"] isEqual:@"SUCCESS"]) //请求成功
        {
            if ([[dic jsonString:@"data"] containsString:@"ptmode=html5"]) {
                EDPTGameDetailViewController * webVC = [EDPTGameDetailViewController new];
                if (model.orientation.integerValue ==2)
                {
                    webVC.allowRotation = NO;
                }else
                {
                    webVC.allowRotation = YES;
                }
                webVC.urlStr = [dic jsonString:@"data"] ;
                [self.navigationController pushViewController:webVC animated:YES];
            }else{
                
                LLWebViewController * webview = [[LLWebViewController alloc] init];
                webview.urlStr = dic[@"data"];
                
                if (model.orientation.integerValue ==2)
                {
                     webview.isType = 2;
                }else
                {
                     webview.isType = 3;
                }
               
                [self.navigationController pushViewController:webview animated:YES];
            }
       
        }else
        {
             [JMNotifyView showNotify:[dic jsonString:@"message"]  isSuccessful:NO];
        }
        
        
    } failure:^(id responseObject, NSError *error) {
         [self stopLoadingAnimation];
        [WJUnit showMessage:@"请求错误"];
        
    }];
}
//定义每个Section的四边间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0.5, 0.5, 0.5, 0.5);//分别为上、左、下、右
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size = CGSizeMake(UIScreenWidth/3 -1 ,140);
    return size;
}
//两个cell之间的间距（同一行的cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return RealValue_W(0.5);
}
//这个是两行cell之间的间距（上下行cell的间距）
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return RealValue_W(1);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    Mine *mine = _dataSource[indexPath.row];
//    ServerDetailsViewController * ServerDetailsVC = [[ServerDetailsViewController alloc] init];
//    ServerDetailsVC.hidesBottomBarWhenPushed = YES;
//    ServerDetailsVC.title = @"服务器详情";
//    ServerDetailsVC.server_id = mine.id;
//    [self.navigationController pushViewController:ServerDetailsVC animated:YES];;
}
@end
